package cc.imos.communal.kit;

import cc.imos.communal.err.ErrCode;
import cc.imos.communal.err.ErrException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.List;

/**
 * <pre>
 *     Web Kit
 * Created by asher on 2017/6/3.
 * </pre>
 */
public class WebKit {

    /**
     * Spring hasErrors
     *
     * @param bindingResult
     * @throws ErrException
     */
    public static void hasErrors(BindingResult bindingResult) throws ErrException {
        if(bindingResult.hasErrors()) {
            StringBuilder sb = new StringBuilder();
            List<ObjectError> errors = bindingResult.getAllErrors();
            for (ObjectError error: errors) {
                sb.append(",");
                sb.append(error.getDefaultMessage());
            }
            String message = sb.toString().replaceFirst(",", "");
            throw new ErrException(ErrCode.err_args, message);
        }
    }
}
